package main

import (
	"fmt"
	"time"
)

/*
	实现一个缓存，能够存储任何数据，一定时间后自动清除
*/

type CacheValue struct {
	val   interface{}
	timer *time.Timer
}

var datas = make(map[string]*CacheValue)

func put(key string, val interface{}, duration int64) {
	if cacheValue, ok := datas[key]; ok {
		cacheValue.val = val
		cacheValue.timer.Reset(time.Duration(duration) * time.Second)

	} else {
		timer := time.NewTimer(time.Duration(duration) * time.Second)

		datas[key] = &CacheValue{val: val, timer: timer}
		go func() {
			select {
			case <-timer.C:
				delete(datas, key)
			}
		}()
	}
}

func get(key string) interface{} {
	if cacheValue, ok := datas[key]; ok {
		return cacheValue.val
	}
	return nil
}

func main() {
	put("a", 11, 3)
	time.Sleep(2 * time.Second)
	put("a", "aaa你好", 3)
	time.Sleep(2 * time.Second)
	fmt.Println(get("a"))
}
